package tungsten.base.utils;

import tungsten.base.thread.ThreadPool;

import java.util.concurrent.*;

/**
 * Created by Lv on 2016/6/29.
 */
public class TimerUtils
{
    private static final String TIMER_THREAD = "TIMER_THREAD";

    /**
     * 当前的时间，毫秒数
     */
    private static long currentTimeMillis;
    private static int currentTimeSeconds;
    /**
     * 设置的时间
     */
    private static long setTimeMillis = 0;
    /**
     * 设置时间的时候的 毫秒值
     */
    private static long setTimeSystemMillis = 0;

    private static ScheduledThreadPoolExecutor threadPool;

    public static void initialize()
    {
        initialize(1);
    }

    public static void initialize(int thread)
    {
        threadPool = ThreadPool.scheduleThreadPool(TIMER_THREAD, thread);

        threadPool.scheduleAtFixedRate(() ->
        {
            currentTimeMillis = setTimeMillis + System.currentTimeMillis() - setTimeSystemMillis;
            currentTimeSeconds = (int) (currentTimeMillis * 0.001);

        },0,33L,TimeUnit.MILLISECONDS);
    }

    public static ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)
    {
        return threadPool.scheduleAtFixedRate(command,initialDelay,period,unit);
    }

    public ScheduledFuture<?> schedule(Runnable command,long delay,TimeUnit unit)
    {
        return threadPool.schedule(command,delay,unit);
    }

    /**
     * 获取当前时间，毫秒数
     * @return
     */
    public static long currentTimeMillis() {
        return currentTimeMillis;
    }

    /**
     * 当前的秒数
     * @return
     */
    public static int currentTimeSeconds()
    {
        return currentTimeSeconds;
    }
}
